# Appendix S2: R code used for INLA analysis

library(ResourceSelection)
library(glmmTMB)
library(INLA)

ponga<-read.csv("ponga_data.csv", header=TRUE)

#scale and center numerical variables
ponga$Length_cm <- scale(ponga$Length_cm)
ponga$Diameter_top_cm <- scale(ponga$Diameter_top_cm)

#code to repeat ID variable for INLA mixed model analysis
ponga$ID2<-ponga$ID3<-ponga$ID

#preciosion of priors
prec.beta.Length_cm<-1e-4
prec.beta.Diameter_top_cm<-1e-4

formula.inla<-ponga$Nest_use~ponga$Length_cm + ponga$Diameter_top_cm +
f(ponga$ID,model="iid", hyper=list(theta=list(initial=log(1e-6),fixed=T))) +
f(ponga$ID2, ponga$Length_cm, values=1:3, model="iid",
hyper=list(theta=list(initial=log(1),fixed=F,prior="pc.prec",param=c(1,0.05)))) +
f(ponga$ID3, ponga$Diameter_top_cm, values=1:3, model="iid",
hyper=list(theta=list(initial=log(1),fixed=F,prior="pc.prec",param=c(1,0.05))))

ponga$weight<-1000^(1-ponga$Nest_use)

ponga.inla<-inla(formula.inla,family="binomial", Ntrials=1, data=ponga,weights=ponga$weight,
control.fixed=list(mean=0,prec=list(Length_cm = prec.beta.Length_cm ,
Diameter_top_cm = prec.beta.Diameter_top_cm)
)
)

summary(ponga.inla)

#Function to obtain posterior means of marginals from an inla object
inla_emarginal <- function(r.out){ 
results <- sapply(r.out$marginals.hyperpar, 
       function(y) 
         inla.emarginal(function(x) x, inla.tmarginal(function(x) 1/x, y)))

names(results) <- sapply(as.vector(as.character(names(results))), function(y) gsub("Precision", x=y, "Mean of variance"))
  results
}


inla_emarginal(ponga.inla)

#Function to obtain posterior modes of marginals from an inla object
inla_mmarginal <- function(r.out){ 
results <- sapply(r.out$marginals.hyperpar, 
       function(y) 
         inla.mmarginal(inla.tmarginal(function(x) 1/x, y)))

names(results) <- sapply(as.vector(as.character(names(results))), function(y) gsub("Precision", x=y, "Mode of variance"))
  results
}

inla_mmarginal(ponga.inla)



